<template>
  <div>
    <h3 style="margin-bottom:20px">{{ id ? '编辑' : '创建' }}用户</h3>
    <el-form label-width="80px" :model="model" @submit.native.prevent="save">
      <el-form-item label="用户名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="用户账号">
        <el-input v-model="model.username"></el-input>
      </el-form-item>
      <el-form-item label="用户密码">
        <el-input v-model="model.password"></el-input>
      </el-form-item>
      <el-form-item label="用户简介">
        <el-input type="textarea" v-model="model.desc"></el-input>
      </el-form-item>
      <el-form-item label="用户头像">
        <el-upload
          class="avatar-uploader"
          :action="$http.defaults.baseURL + '/upload'"
          :show-file-list="false"
          :on-success="res => $set(model, 'avatar', res.url)"
        >
          <img v-if="model.avatar" :src="model.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">{{
          id ? '保存变更' : '立即创建'
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: ['id'],
  data() {
    return {
      model: {}
    }
  },
  methods: {
    async save() {
      if (this.id) {
        await this.$http.put(`/common/user/${this.id}`, this.model)
      } else {
        await this.$http.post('/common/user', this.model)
      }
      this.$router.push('/user/list')
      this.$message({
        type: 'success',
        message: '创建成功'
      })
    },
    async fetch() {
      const res = await this.$http.get(`/common/user/${this.id}`)
      this.model = res.data
    }
  },
  created() {
    this.id && this.fetch()
  }
}
</script>

<style></style>
